import { processNodeForm } from '../types/processNodeForm'
import { modelerElement } from '../types/modeler'

import { nodeTaskTypeValue } from '@/enums/constant'
import { cloneDeep } from 'lodash-es'
import { isNullOrEmpty, isEmpty } from '@/utils/is'

import { useI18n } from '@/locales'
const { t } = useI18n()

/**
 * 生成一个审批节点的表单数据
 * @param modelerElement 流程图插件的一个元素（节点或连线）
 * @returns {processNodeForm}
 */
export function generateProcessNodeForm(modelerElement: modelerElement): processNodeForm {
    const { id, type } = modelerElement

    // 根据不同节点类型生成不同的节点名称
    let processNodeName = ''
    switch (type) {
        case 'bpmn:StartEvent':
            processNodeName = '申请人'
            break
        case 'bpmn:EndEvent':
            processNodeName = '结束'
            break
    }

    // 获取当前节点的连线信息
    const { sourceRef, targetRef } = generateConnectionInfo(modelerElement)

    return {
        sourceRef,
        targetRef,
        processNodeId: id,
        processNodeType: type,
        processNodeName,
        rollbackNodeFlag: true, // 是否是回退节点
        nodeTaskType: nodeTaskTypeValue.APPROVE, // 节点任务类型
        basePermission: {
            processRollbackFlag: true, // 流程回退标识
            processRejectFlag: true, // 流程拒绝标识
            submitFlag: true, // 提交标识
            saveFlag: true, // 保存标识
            formEditPermissionFlag: true, // 表单编辑权限标识
            rollbackNodeRange: 'ONE_BEFORE_NODE' // 回退节点默认值
        },
        reportPermission: {
            associatedReportFlag: false, // 关联报表标识
            reportConfig: '', // 报表配置
            defaultDisplayContent: 'FORM' // FORM（表单） || REPORT（报表） 默认展示内容
        },
        responsiblePerson: {
            approveUserType: 'DESIGNATED_MEMBER',
            approverList: [], // 负责人列表
            responsiblePersonMap: null
        },
        approveUser: {
            approveType: 'JOINTLY', // 审批人分类
            approveUserType: 'DESIGNATED_MEMBER', // 审批人类型，默认表内成员
            approverList: [],
            departmentIdList: [], // 所选部门
            userGroupIdList: [] // 用户组
        },
        cc: {
            approveUserType: 'DESIGNATED_MEMBER',
            isEnable: false, // 是否启用抄送
            approverList: [],
            departmentIdList: [], // 所选部门
            userGroupIdList: [] // 用户组
        },
        approveButtonConfig: {
            buttonSetting: [
                {
                    name: '同意',
                    showName: '同意',
                    batchApprovalFlag: false,
                    enable: true
                },
                {
                    name: '拒绝',
                    showName: '拒绝',
                    batchApprovalFlag: false,
                    enable: true
                },
                {
                    name: '退回',
                    showName: '退回',
                    batchApprovalFlag: false,
                    enable: true
                }
            ]
        }, // 审批按钮
        automaticApprovalConfig: {
            initiatorAutomaticApprovalFlag: false, // 发起人自动审批
            adjacentNodeAutomaticApprovalFlag: false // 相邻节点自动审批
        },
        unapprovedUserProcessMethod: 'END_PROCESS', // 自动跳过节点
        condition: {
            rule: []
        },
        pageFieldIdList: [],
        triggerConfiguration: {
            triggerType: 'TIMING_TRIGGER',
            timingTriggerConfiguration: {
                triggerFrequency: 'ONLY_ONCE',
                onlyOnceTriggerConfiguration: {
                    triggerTiming: undefined
                },
                periodTriggerConfiguration: null
            },
            instantTriggerConfiguration: {
                triggerTimingList: []
            },
            toDoValidityPeriodConfiguration: {
                type: 'INDEFINITELY',
                timeUnit: 'DAY',
                length: 0
            },
            triggeringConditions: {
                componentHideRule: {
                    rules: []
                }
            }
        }
    }
}

// 获取流程图元素的连线信息
export function generateConnectionInfo(modelerElement) {
    const { type, businessObject } = modelerElement
    if (type !== 'bpmn:SequenceFlow') {
        return {
            sourceRef: {},
            targetRef: {}
        }
    }

    const source = businessObject.sourceRef ? businessObject.sourceRef : modelerElement.source

    const target = businessObject.sourceRef ? businessObject.targetRef : modelerElement.target

    const { $type: sourceType, id: sourceId } = source
    const { $type: targetType, id: targetId } = target

    return {
        sourceRef: { flowNodeId: sourceId, flowNodeType: sourceType },
        targetRef: { flowNodeId: targetId, flowNodeType: targetType }
    }
}

// 格式化流程节点的表单数据：对老数据做兼容、按照接口要求转换数据
export function formatProcessNodeForm(processNodeList) {
    return cloneDeep(processNodeList).map(processNodeForm => {
        const { processNodeType, condition } = processNodeForm

        // 兼容老的数据解构：如果不存在condition则给其赋默认值
        // 此处不知道兼容的是什么时候的老数据，暂未删除 大重构后
        if (!condition || !condition.rule) {
            processNodeForm.condition = { rule: [] }
        }
        // 兼容老数据，判断是否是直接保存，审批人为空时
        if (
            processNodeForm.nodeTaskType === nodeTaskTypeValue.APPROVE &&
            isNullOrEmpty(processNodeForm.unapprovedUserProcessMethod)
        ) {
            processNodeForm.unapprovedUserProcessMethod = 'END_PROCESS'
        }
        // 兼容老数据，判断是否是直接保存 选择审批人类型
        if (
            processNodeForm.nodeTaskType === nodeTaskTypeValue.APPROVE &&
            isNullOrEmpty(processNodeForm.approveUser.approveUserType)
        ) {
            processNodeForm.approveUser.approveUserType = 'DESIGNATED_MEMBER'
        }

        // 转换节点类型
        processNodeForm.processNodeType = processNodeType.replace(/bpmn:/g, '')
        return processNodeForm
    })
}

// 格式化后端返回的节点表单数据，用于前端回显
export function formatResponseProcessNodeForm(processNodeFormList, pageDetail) {
    return cloneDeep(processNodeFormList).map(processNodeForm => {
        // 兼容老数据处理 老数据没有抄送人
        if (isNullOrEmpty(processNodeForm.cc)) {
            processNodeForm.cc = {
                isEnable: false, // 是否启用抄送
                approverList: []
            }
        }
        // 是否开启抄送
        processNodeForm.cc.isEnable = processNodeForm.cc.approverList.length !== 0

        // 格式化节点类型
        if (processNodeForm.processNodeType.indexOf('bpmn:') === -1) {
            processNodeForm.processNodeType = `bpmn:${processNodeForm.processNodeType}`
        }

        // 重组字段权限属性
        const pageFieldIdList: any[] = []
        // 以最新的发布页面表单组件为基础
        pageDetail.forEach(page => {
            let filedItem = { ...page } // 默认使用新组件信息
            processNodeForm.pageFieldIdList.forEach(pageFieldId => {
                // 老数据如果含有当前表单字段， 就使用原有数据的权限
                if (pageFieldId.filedId === page.filedId) {
                    filedItem = {
                        componentName: page.componentName,
                        editableFlag: pageFieldId.editableFlag, // 可编辑不可编辑 以原数据为准
                        filedId: page.filedId,
                        filterColumnName: page.key,
                        type: page.type,
                        label: page.label,
                        visibilityFlag: pageFieldId.visibilityFlag // 可见不可见 以原数据为准
                    }
                }
            })
            pageFieldIdList.push(filedItem)
        })
        processNodeForm.pageFieldIdList = pageFieldIdList

        return processNodeForm
    })
}

// 校验流程节点数据是否合法
export function checkProcessNodeFormList(processNodeList) {
    const resInfo = {
        error: false,
        msg: '',
        data: []
    }
    const nodeInfo = {
        hasStart: false, // 是否有开始节点
        hasEnd: false, // 是否有结束节点
        hasSequenceFlow: false, // 是否有连线
        hasTask: false, // 是否有任务
        startCount: 0, // 开始节点个数
        formId: false, // 是否关联数据源
        endCount: 0 // 结束节点个数
    }

    processNodeList.forEach(item => {
        // 连线节点只检查排它条件
        if (item.processNodeType === 'bpmn:SequenceFlow') {
            nodeInfo.hasSequenceFlow = true
            item.condition?.rule.forEach(expression => {
                if (isEmpty(expression.rule) || isNullOrEmpty(expression.id)) {
                    resInfo.error = true
                    resInfo.msg = t('workflow.checkError.notBusinessObject')
                }
            })

            // 检查有没有开始直接到结束的关系线
            if (
                (item.sourceRef.flowNodeType === 'bpmn:StartEvent' &&
                    item.targetRef.flowNodeType === 'bpmn:EndEvent') ||
                (item.targetRef.flowNodeType === 'bpmn:StartEvent' && item.sourceRef.flowNodeType === 'bpmn:EndEvent')
            ) {
                resInfo.error = true
                resInfo.msg = t('workflow.checkError.notStartAndEnd')
            }

            // 只检查任务节点的抄送和审批人信息和负责人信息
        } else if (item.processNodeType.indexOf('Task') > -1) {
            nodeInfo.hasTask = true
            // 审批节点才需要判断审批人
            if (item.nodeTaskType === nodeTaskTypeValue.APPROVE && !item.approveUser.approverList.length) {
                resInfo.error = true
                resInfo.msg = t('workflow.checkError.notApproveUser')
            }
            // 填报节点需要判断负责人
            if (item.nodeTaskType === nodeTaskTypeValue.SUBMIT && !item.responsiblePerson.approverList.length) {
                resInfo.error = true
                resInfo.msg = t('workflow.checkError.notResponsiblePerson')
            }
            // 检查是否填写节点名称
            if (isNullOrEmpty(item.processNodeName)) {
                resInfo.error = true
                resInfo.msg = t('workflow.checkError.notProcessNodeName')
            }
            // 检查抄送人是否存在
            if (item.cc.isEnable && !item.cc.approverList.length) {
                resInfo.error = true
                resInfo.msg = t('workflow.checkError.notCc')
            }
        } else if (item.processNodeType === 'bpmn:StartEvent') {
            nodeInfo.hasStart = true
            ++nodeInfo.startCount
        } else if (item.processNodeType === 'bpmn:EndEvent') {
            nodeInfo.hasEnd = true
            ++nodeInfo.endCount
        }
        // 判断是否选择关联数据源
        if (item.associatedDataSource) {
            nodeInfo.formId = true
        }

        // 检测连线关联关系
        if (item.processNodeType !== 'bpmn:SequenceFlow') {
            let hasRelationship = false // 是否有关系
            processNodeList.forEach(sequenceFlow => {
                if (
                    sequenceFlow.sourceRef.flowNodeId === item.processNodeId ||
                    sequenceFlow.targetRef.flowNodeId === item.processNodeId
                ) {
                    hasRelationship = true
                }
            })
            if (!hasRelationship) {
                resInfo.error = true
                resInfo.msg = t('workflow.checkError.relationshipError')
            }
        }
    })

    // 判单开始结束节点是否存在多个
    if (nodeInfo.startCount > 1 || nodeInfo.endCount > 1) {
        resInfo.error = true
        resInfo.msg = t('workflow.checkError.surplusNode')
    }
    // 返回数据错误信息
    if (resInfo.error) {
        return resInfo
    }
    // 检查是否关联数据源
    if (!nodeInfo.formId) {
        resInfo.error = true
        resInfo.msg = t('workflow.checkError.associatedDataSource')
        return resInfo
    }
    // 检查是否包含  开始 结束 任务 连线
    if (!nodeInfo.hasStart || !nodeInfo.hasEnd || !nodeInfo.hasTask || !nodeInfo.hasSequenceFlow) {
        resInfo.error = true
        resInfo.msg = t('workflow.checkError.notComplete')
        return resInfo
    }

    // 返回错误信息
    if (resInfo.error) {
        return resInfo
    }

    return resInfo
}
